const formatTime = (date, joinSymbol = '/') => {
  const year = date.getFullYear()
  const month = formatNumber(date.getMonth() + 1)
  const day = formatNumber(date.getDate())
  const week = formatWeek(date.getDay())
  const hour = formatNumber(date.getHours())
  const minute = formatNumber(date.getMinutes())
  const second = formatNumber(date.getSeconds())
  return {
    result: [year, month, day].map(formatNumber).join(joinSymbol) + ' ' + [hour, minute, second].map(formatNumber).join(':'),
    date: [year, month, day].map(formatNumber).join(joinSymbol),
    chinaDate: `${year}年${month}月${day}日`,
    clock: [hour, minute, second].map(formatNumber).join(':'),
    year,
    month,
    week,
    day,
    hour,
    minute,
    second
  }
}
const formatWeek = week => {
  return parseInt(week.toString()) || 7
}
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

const generateMonthTotalDays = (_year, _month) => {
  /**
   * 获取月份对应天数
   * @author zdd update(2018/7/26)
   */
  let year
  let month
  if (_month) {
    // _month > 0
    year = _year
    month = _month
  } else {
    // _month <= 0 返回去年12月
    year = _year - 1
    month = 12
  }
  return [31, (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0 ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1]
}

const enterSubmit = (method) => {
  /**
   * enter事件
   * @param {Function} method 监测到enter事件时触发的事件
   * @author zdd update(2018/2/7)
   * */
  document.onkeydown = (ev) => {
    const theEvent = ev || window.event
    if (theEvent.keyCode === 13) {
      method()
    }
  }
}

const setCookie = (cookieName, value, expireMinute) => {
  /**
   * 设置cookie
   * @param {string} cookieName cookie名称
   * @param  value   cookieName 对应的值
   * @param {number} expires 失效时间
   * @author zdd update(2018/2/2)
   * */
  const exDate = new Date()
  exDate.setTime(exDate.getTime() + expireMinute * 60 * 1000)
  document.cookie = cookieName + '=' + value + ((expireMinute === null) ? '' : ';expires=' + exDate.toGMTString())
}

const getCookie = (name) => {
  /**
   * 获取cookie
   * @param {String} name cookieName
   * @author zdd update(2018/2/2)
   * */
  let arr
  const reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)')
  return (arr = document.cookie.match(reg)) ? arr[2] : null
}

const delCookie = (name) => {
  /**
   * 删除cookie
   * @param {string} name cookie名称
   * @author zdd update(2018/2/2)
   * */
  const expires = new Date()
  expires.setTime(expires.getTime() - 1)
  const cookieValue = getCookie(name)
  if (cookieValue !== null) {
    document.cookie = name + '=' + cookieValue + ';expires=' + expires.toGMTString()
  }
}
const checkLogin = () => {
  /**
   * 检测是否登陆失效
   * @author zdd update(2018/2/2)
   * */
  return !!getCookie('isLogin')
}

const reNameDocTitle = (to) => {
  /**
   * 重命名document.title(根据route.name)
   * @param {Object} to 路由跳转到的路由对象
   * @author zdd update(2018/1/31)
   * */
  const routeName = to.meta.title || to.name
  window.document.title = (routeName ? `${routeName} - ` : '') + '健康管理'
}

const isArray = item => {
  return Object.prototype.toString.call(item) === '[object Array]'
}

const formatStatus = status => {
  /**
   * 格式化服务器内部返回状态值
   * @param team_健康管理
   * @param {String | Number} status 0/'0' 成功 1/'1' 失败 -2/'-2'未登录或登录失效
   * @returns {Number} status 状态字
   */
  return status * 1
}
const formatGenderToServe = type => {
  const gender = {
    '男': '1',
    '女': '2',
    '未知': '0'
  }
  return gender[type] || '9'
}
const avatarImage = (gender) => {
  /**
   * 处理病人头像
   * @param {String} gender 性别
   */
  const type = gender === '男' ? 'img-man' : 'img-woman'
  return require(`../../static/images/${type}.png`)
}
const fetchSuccess = res => {
  /**
   * 判断请求数据是否成功
   * @param {Object} res 服务端返回对象
   */
  const entity = res.data // 服务端返回的业务实体（Object）
  return res && entity && entity.status && (formatStatus(entity.status) === 0)
}
const fixedNumber = (val, num) => {
  /**
   * 保留几位小数点
   * @param {Number} val 需要被处理的值
   * @param {Number} num 需要保留的位数
   * @return {Number} 处理后的值
   */
  const valToString = typeof val === 'number' ? val + '' : val
  const posIndex = valToString.indexOf('.')
  return posIndex > -1 ? valToString.substring(0, posIndex + 1 + num) : val
}
const formatPatientToApp = info => {
  /**
   * 格式化用户数据to app
   * @param {Object} info 用户信息
   * @return {Object} 格式化后的信息
   */
  const { xm, xbdis, nl, sfzh, lxdh, jzdz, yngrbsh } = info
  return {
    name: xm || '不详',
    gender: xbdis || '不详',
    age: nl || '不详',
    idCard: sfzh || '不详',
    telephone: lxdh || '不详',
    address: jzdz || '不详',
    primaryKey: yngrbsh || null,
    status: {}
  }
}

const debounce = (fn, interval) => {
  /**
   * 防抖
   * @param {Function} fn 回调函数
   * @param {Number} interval 时间间隔
   * @return {Function}
   */
  let timeout = null
  return () => {
    if (timeout !== null) clearTimeout(timeout)
    timeout = setTimeout(fn, interval || 350)
  }
}
const isEmptyValue = (val) => {
  /**
   * 判断项目是否为空值
   * @param {Object} val
   */
  let isEmpty = false
  if (isArray(val)) {
    // 空数组
    if (!val.length) isEmpty = true
  } else {
    // 字符串
    if (val === '') isEmpty = true
  }
  return isEmpty
}
const formatToRealXml = data => {
  /**
   * 格式化xml数据
   * @param {String} data sbxml
   * @return xml
   */
  const step1 = data.slice(data.indexOf('&lt;'), data.lastIndexOf('&gt;') + 4)
  const step2 = step1.replace(/&lt;/g, '<')
  return step2.replace(/&gt;/g, '>')
}
/**
 * 校验客户端
 * true 为PC，false 为移动端
 */
const checkClientType = () => {
  let userAgentInfo = navigator.userAgent
  let Agents = ['Android', 'iPhone', 'SymbianOS', 'Windows Phone', 'iPad', 'iPod']
  let flag = true
  for (var v = 0; v < Agents.length; v++) {
    if (userAgentInfo.indexOf(Agents[v]) > 0) { flag = false; break }
  }
  return flag
}

const convertArguments = (data) => {
  let ret = ''
  for (let it in data) {
    ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
  }
  console.log(ret)
  if (ret.endsWith('&')) {
    ret = ret.substr(0, ret.length - 1)
  }
  return ret
}

const screenScale = () => {
  let width = window.screen.width
  let scale = 1.6
  switch (width) {
    case 1920:
      scale = 2
      break
    case 1366:
      scale = 1.5
      break
    default:
      scale = 1.6
  }
  return scale
}
module.exports = {
  formatTime,
  formatNumber,
  enterSubmit,
  setCookie,
  getCookie,
  delCookie,
  checkLogin,
  generateMonthTotalDays,
  reNameDocTitle,
  isArray,
  screenScale,
  formatStatus,
  formatGenderToServe,
  avatarImage,
  fetchSuccess,
  fixedNumber,
  formatPatientToApp,
  debounce,
  isEmptyValue,
  formatToRealXml,
  checkClientType,
  convertArguments
}
